package commander;

import fileoperation.FileReader;
import gitobject.*;
import sha1.SHA1;
import repository.*;
import fileoperation.*;


import java.io.*;
import java.util.ArrayList;


/*
说明：
1、通过git rm [filename]的命令，将文件从暂存区中删除
2、基本就是git add 的逆操作，注意不要将工作区的文件删除了
3、注意打印异常信息（删除一个不存在暂存区的文件）

 */
public class rm extends Command {
    public void rm(String fileName) throws Exception {
        String indexContent = FileReader.readFileValue(this.index);
        ArrayList<String> indexList = FileReader.readByBufferReader(indexContent);
        String objectName = " ";
        //逐行读取index中字符存入indexList
        File f = new File(workingDir + fileName);
        if (!f.exists()) {
            System.out.println("file not exists");
            return;
        }
        if(f.isFile()){//若filename是一个文件
            try {
                Blob blob = new Blob(f);
                objectName = blob.toString();
//            append = "10064 tree " + new SHA1CheckSum(f).getSha1() + " " + f.getName();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        else {
            try {
                Tree tree = new Tree(f);
                objectName = tree.toString();
//            append = "040000 tree " + new SHA1CheckSum(f).getSha1() + " " + f.getName();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        //遍历删除ArrayList指定值，参考11.26作业
        for(int i = 0; i < indexList.size();i++){
            if(indexList.get(i).equals(objectName)){
                indexList.remove(i);
            }
        }
        //删除后的ArrayList写入index
        FileDeletion.deleteFile(this.index);
        FileWriter fw = new FileWriter(this.index, true);//true表示字节写入末尾
        PrintWriter pw = new PrintWriter(fw);
        for(int i = 0; i < indexList.size();i++){
            pw.println(indexList.get(i));
        }
        fw.close();
        pw.close();
    }
}

